import { fileURLToPath, URL } from 'node:url'
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import AutoImport from 'unplugin-auto-import/vite'
import { createHtmlPlugin } from 'vite-plugin-html'
import legacyPlugin from '@vitejs/plugin-legacy'
import { config } from 'dotenv'
import path from 'path'
// 载入 .env 文件中的环境变量
const modeIndex = process.argv.findIndex((item, index) => {
  if (item.includes('mode')) {
    return index
  }
})
const envFile = '.env.' + process.argv[modeIndex + 1]
config({ path: path.resolve(__dirname, './', envFile) })
// https://vitejs.dev/config/ vite配置
export default defineConfig({
  // 读取env配置
  // envDir: './src/config',
  // 路由前缀配置
  base: process.env.VITE_BASE_URL,
  // 打包文件的输出目录
  build: {
    outDir: 'build',
    //生成静态资源的存放路径
    assetsDir: 'assets',
    //打包环境移除console.log，debugger
    minify: 'terser',
    terserOptions: {
      compress: {
        drop_console: process.env.NODE_ENV === 'production' ? true : false,
        drop_debugger: process.env.NODE_ENV === 'production' ? true : false,
      },
    },
    //打包文件按照类型分文件夹显示
    rollupOptions: {
      input: {
        main: path.resolve(__dirname, './public/index.html'),
      },
      output: {
        chunkFileNames: 'js/[name]-[hash].js',
        entryFileNames: 'js/[name]-[hash].js',
        assetFileNames: '[ext]/[name]-[hash].[ext]',
        manualChunks(id) {
          // 静态资源分拆打包
          if (id.includes('node_modules')) {
            return id.toString().split('node_modules/')[1].split('/')[0].toString()
          }
        },
      },
    },
  },
  // 将 Node.js 环境变量传递给应用程序
  define: {
    'process.env': process.env,
  },
  // 插件配置
  plugins: [
    vue(),
    vueJsx(),
    Components({
      resolvers: [ElementPlusResolver({ importStyle: 'sass' })],
    }),
    AutoImport({
      imports: ['vue', 'vue-router'], // 自动导入vue和vue-router相关函数
      resolvers: [ElementPlusResolver()],
    }),
    legacyPlugin({
      targets: ['chrome 52'], // 需要兼容的目标列表，可以设置多个
      additionalLegacyPolyfills: ['regenerator-runtime/runtime'], // 面向IE11时需要此插件
    }),
    createHtmlPlugin({
      inject: {
        data: {
          //获取标题变量
          programTitle: '模板',
        },
      },
    }),
  ],
  // 本地服务配置
  server: {
    open: true, // 设置服务启动时是否自动打开浏览器
    cors: true, // 允许跨域
    // host: '0.0.0.0',
    proxy: {
      '/api': {
        // 样例，按实际接口调整
        target: 'http://yapi.hrfax.example/mock/1055',
        changeOrigin: true,
        rewrite: path => path.replace(/^\/api/, ''),
      },
    },
  },
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url)),
    },
  },
  css: {
    preprocessorOptions: {
      scss: {
        additionalData: `@use './src/assets/variables.scss' as *;@use './src/assets/scss/${
          process.argv[modeIndex + 1]
        }.scss' as *;`, // 此处全局的scss文件
      },
    },
  },
})
